package com.platform.usercenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.usercenter.domain.SysMenuTreeDTO;
import com.platform.usercenter.domain.SysMiniProgramMenu;
import com.platform.usercenter.domain.dto.SelectOptionDTO;
import com.platform.usercenter.domain.dto.SysMenuPermissionDTO;
import com.platform.usercenter.mapper.SysMiniProgramMenuMapper;
import com.platform.usercenter.service.ISysMiniProgramMenuService;
import com.platform.usercenter.utils.TreeAdapterUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 小程序菜单接口
 * @Author: wcs
 * @Date: 2024-11-17 11:17:19
 **/
@Service
public class ISysMiniProgramMenuServiceImpl implements ISysMiniProgramMenuService {

    @Resource
    SysMiniProgramMenuMapper sysMiniProgramMenuMapper;

    @Override
    public AjaxResult saveSysMiniProgramMenu(List<SysMiniProgramMenu> sysMiniProgramMenus) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null || loginUser.getSysUser().getUserId() == null) {
            return AjaxResult.error("userId is empty");
        }
        Long userid = loginUser.getSysUser().getUserId();
        Long orgId = loginUser.getOrgId();
        //配置表先删除
        SysMiniProgramMenu sysMiniProgramMenu = new SysMiniProgramMenu();
        sysMiniProgramMenu.setUserId(userid);
        sysMiniProgramMenu.setOrgId(orgId);
        sysMiniProgramMenuMapper.deleteMiniProgramMenuByCode(sysMiniProgramMenu);
        //新增卡片配置
        if (StringUtils.isNotEmpty(sysMiniProgramMenus)) {
            Date today = new Date();
            for (SysMiniProgramMenu miniProgramMenu : sysMiniProgramMenus) {
                miniProgramMenu.setUserId(userid);
                miniProgramMenu.setOrgId(orgId);
                miniProgramMenu.setCreateBy(loginUser.getUsername());
                miniProgramMenu.setCreateTime(today);
                sysMiniProgramMenuMapper.insertMiniProgramMenuConfig(miniProgramMenu);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public List<SysMenuTreeDTO> getUserMiniProgramMenuList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysMiniProgramMenu sysMiniProgramMenu = new SysMiniProgramMenu();
        sysMiniProgramMenu.setUserId(loginUser.getSysUser().getUserId());
        sysMiniProgramMenu.setOrgId(loginUser.getOrgId());
        List<SysMenuTreeDTO> menus= sysMiniProgramMenuMapper.selectMiniProgramMenuList(sysMiniProgramMenu);
        if (CollectionUtils.isNotEmpty(menus)){
            List<Long> parentIds = menus.stream().map(SysMenuTreeDTO::getMenuId).collect(Collectors.toList());
            List<SysMenuTreeDTO> children=sysMiniProgramMenuMapper.selectMenuByParentIds(parentIds);
            if (CollectionUtils.isNotEmpty(children)){
                Map<Long, List<SysMenuTreeDTO>> childrenMap = children.stream()
                        .collect(Collectors.groupingBy(
                                SysMenuTreeDTO::getParentId
                        ));
                for (SysMenuTreeDTO menu : menus) {
                    menu.setChildren(childrenMap.get(menu.getMenuId()));
                }
            }
        }
        if(CollectionUtils.isNotEmpty(menus)){
            dealMenuPermission(menus);
            return menus;
        }else {
            return null;
        }
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenuTreeDTO> getChildPerms(List<SysMenuTreeDTO> list, int parentId) {
        List<SysMenuTreeDTO> returnList = new ArrayList<>();
        for (Iterator<SysMenuTreeDTO> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenuTreeDTO t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                TreeAdapterUtil.recursionFn(list, t, SysMenuTreeDTO.class);
                returnList.add(t);
            }
        }
        return returnList;
    }

    private void dealMenuPermission(List<SysMenuTreeDTO> menus) {
        if (!CollectionUtils.isEmpty(menus)) {
            for (SysMenuTreeDTO menu : menus) {
                if (!CollectionUtils.isEmpty(menu.getMenuPermissionDTOS())) {
                    List<SysMenuPermissionDTO> permissionDTOS = getMenuPermission(menu);
                    menu.setMenuPermissionDTOS(permissionDTOS);
                }
            }
        }
    }


    private List<SysMenuPermissionDTO> getMenuPermission(SysMenuTreeDTO menu) {
        List<SysMenuPermissionDTO> menuPermissionDTOS = new ArrayList<>();
        //根据菜单的数据权限key进行分组
        Map<String, List<SysMenuPermissionDTO>> listMap = menu.getMenuPermissionDTOS().stream().collect(Collectors.groupingBy(SysMenuPermissionDTO::getKeyCode));
        for (Map.Entry<String, List<SysMenuPermissionDTO>> entry : listMap.entrySet()) {
            List<SysMenuPermissionDTO> dtoList = listMap.get(entry.getKey());
            List<SelectOptionDTO> optionDTOS = new ArrayList<>();
            for (SysMenuPermissionDTO permissionDTO : dtoList) {
                optionDTOS.addAll(JSON.parseArray(permissionDTO.getKeyValue(), SelectOptionDTO.class));
            }
            Map<String, String> keyValueMap = new HashMap<>();
            for (SelectOptionDTO dto : optionDTOS) {
                if (!keyValueMap.containsKey(dto.getValue())) {
                    keyValueMap.put(dto.getValue(), dto.getLabel());
                }
            }


            List<SelectOptionDTO> keyOptionDTO = new ArrayList<>();
            for (Map.Entry<String, String> value : keyValueMap.entrySet()) {
                SelectOptionDTO optionDTO = new SelectOptionDTO();
                optionDTO.setLabel(value.getValue());
                optionDTO.setValue(value.getKey());
                keyOptionDTO.add(optionDTO);
            }

            SysMenuPermissionDTO menuPermissionDTO = new SysMenuPermissionDTO();
            menuPermissionDTO.setKeyCode(entry.getKey());
            menuPermissionDTO.setSelectOptionDTOS(keyOptionDTO);
            menuPermissionDTOS.add(menuPermissionDTO);
        }
        return menuPermissionDTOS;
    }


}
